// variables referenced in fileuploader.js
var receivedXsd = (new Test()).Dummy_Xsd();
var elementsList;
var pNode;
var unionChildren;

function createInsertChild(identifier, parentNode) {
	var nodeInfo = elementsList[identifier];
	var id = nodeInfo["id"];
	pNode = $(parentNode).children("ul");
	unionChildren = nodeInfo["unionChildren"];
	
	var formHTML = "<table class='table' id='add-tbl'>" 
		+ "<thead><tr><th>Element sequence</th>"
		+ "<th>Reorderable?</th>"
		+ "<th>Quantity</th></tr></thead><tbody>";
	for(var i=0; i<unionChildren.length; i++){
		// unionChildren is ALWAYS the parent of sequenceChildren
		var sequenceChildren = unionChildren[i]["sequenceChildren"][0];
		var seqChildrenIds = "";
		var normalChildren = sequenceChildren["normalChildren"];
		var reorderabled = (sequenceChildren["reorderabled"]) ? "Yes" : "No";
		
		
		// if maxOccurs is still > 0, allow user to add one more child of this type
		var maxOccurs = unionChildren[i]["maxOccurs"];
		var minOccurs = unionChildren[i]["minOccurs"];
		
		for(var j=0; j<normalChildren.length; j++){
			seqChildrenIds += "&lt" + normalChildren[j]["childName"] + "&gt";
		}
		var times = "<input type='number' value='0' class='quantity' readonly />";
		// minOccurs is equal to maxOccurs AND minOccurs > 0 => need to add these children compulsory
		if (maxOccurs == "unlimited") {
			times = "<input type='number' class='quantity' min='1' value='1'/>"; 
		}
		else if (maxOccurs > 0){
			if (minOccurs == maxOccurs){
				times = "<input type='number' value='" + minOccurs + "' class='quantity' readonly />";
			}
			else if ((maxOccurs > minOccurs)){
				times = "<input type='number' class='quantity' min='" 
					+ minOccurs + "' max='" + maxOccurs + "' value='1'/>"; 
			}
		}

		formHTML += "<tr><td>" 
			+ seqChildrenIds 
			+ "</td><td>" + reorderabled + "</td>";
		formHTML += "<td>" + times + "</td></tr>";
	}
	formHTML += "</tbody></table>";
	$("#add-form-div-inner").html(formHTML);
}

$("#add-btn").on('click', function(){
	// iterate each quantity input
	var childrenHTML = "";
	$(".quantity").each(function(index){
		var currentSequenceInfo = unionChildren[index];
		var quantity = $(this).val();
		var elementHTML = "";
		
		$(currentSequenceInfo["sequenceChildren"][0]["normalChildren"]).each(function(){
			var childId = this["childId"];
			var type = (typeof elementsList[childId]["unionChildren"] != 'undefined') 
						? 'complex-type' 
						: 'simple-type';
			elementHTML += "<li><div id='"+ childId +"' class='element-div " + type + " unfinished'" 
						+ this["childName"] + "</div><ul></ul></li>";	
		});
		
		for (var i=0; i<quantity; i++) {
			childrenHTML += elementHTML;
		}
	});
	var children = $(childrenHTML).appendTo(pNode);
	$(pNode).treeview({
		add: children
	});
});